﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ST.Application.DepartmentServices.Dtos;
using ST.Domain;
using ST.Domain.Entities;
using ST.Domain.IRepositories;

namespace ST.Application.DepartmentServices
{
    public class DepartmentService : IDepartmentService
    {
        private readonly IMapper _mapper;
        private readonly IDepartmentRepository _repository;

        public DepartmentService(IDepartmentRepository repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        public async Task<List<DepartmentDto>> GetAllListAsync()
        {
            var list = await _repository.GetAllListAsync();
            return _mapper.Map<List<DepartmentDto>>(list.OrderBy(o => o.Code));
        }

        public async Task<PagedList<DepartmentDto>> GetChildrenByParentAsync(Guid parentId, int startPage, int pageSize)
        {
            var pageList =
                await _repository.LoadPageListAsync(startPage, pageSize, o => o.ParentId == parentId, o => o.Code);
            return _mapper.Map<PagedList<DepartmentDto>>(pageList);
        }

        public async Task<bool> InsertAsync(DepartmentDto dto)
        {
            await _repository.InsertAsync(_mapper.Map<Department>(dto), false);
            return await _repository.SaveAsync();
        }

        public async Task<bool> UpdateAsync(DepartmentDto dto)
        {
            await _repository.UpdateAsync(_mapper.Map<Department>(dto), false);
            return await _repository.SaveAsync();
        }

        public async Task DeleteBatchAsync(List<Guid> ids)
        {
            await _repository.DeleteAsync(o => ids.Contains(o.Id));
        }

        public async Task DeleteAsync(Guid id)
        {
            await _repository.DeleteAsync(id);
        }

        public async Task<DepartmentDto> GetAsync(Guid id)
        {
            var dept = await _repository.GetAsync(id);
            return _mapper.Map<DepartmentDto>(dept);
        }
    }
}